const db=require('../db/index.js')

  const getPicLunBo = (req, res) => {
    // 使用连接池查询数据库
    db.query('SELECT * FROM products WHERE 属性 = "轮播图"', (err, results) => {
      if (err) {
        return res.send({
          status: 500,
          message: "查询失败",
        });
      }
      // 返回查询结果
      res.send({
        status: 200,
        data: results,
        message: "查询成功",
      })
    });
  };
  const getPicDaoHan=(req,res)=>{
    db.query('SELECT * FROM products WHERE 属性 = "导航栏"', (err, results) => {
      if (err) {
        return res.send({
          status: 500,
          message: "查询失败",
        });
      }
      // 返回查询结果
      res.send({
        status: 200,
        data: results,
        message: "查询成功",
      })
    });
  };
  const getPicLike=(req,res)=>{
    db.query('SELECT * FROM products WHERE 属性 = "猜你喜欢"', (err, results) => {
      if (err) {
        return res.send({
          status: 500,
          message: "查询失败",
        });
      }
      // 返回查询结果
      res.send({
        status: 200,
        data: results,
        message: "查询成功",
      })
    });
  }
  //跳转接口
  const getTransform=(req,res)=>{
    const {tags} = req.query;
    const result=tags
    db.query('SELECT * FROM products WHERE tags = ?',[result], (err, results) => {
      if (err) {
        return res.send({
          status: 500,
          message: "查询失败",
        });
      }
      // 返回查询结果
      res.send({
        status: 200,
        data: results,
        message: "查询成功",
      })
    });
  }
  //加入购物车接口
  const addCart = (req, res) => {
    const { userId, productId, quantity, price,imageUrl,description } = req.body;
  
    // 检查请求参数是否完整
    if (!userId || !productId || !quantity || !price||!imageUrl ||!description ) {
      return res.send({ status: 400, message: '请求参数不完整' });
    }
  
    // 检查商品是否已经在购物车中
    db.query(
      'SELECT * FROM new_users WHERE id = ?',
      [userId],
      (err, results) => {
        if (err) {
          return res.send({ status: 500, message: '查询用户失败' });
        }
  
        if (results.length > 0) {
          let cart = results[0].cart ? results[0].cart: [];  
          let addNum1 = results[0].addNum || 0;
  
          let productExists = false;
  
          // 遍历购物车中的商品，查找是否已存在该商品
          for (let i = 0; i < cart.length; i++) {
            if (cart[i].productId === productId) {
              // 商品已存在，更新数量
              let num1=Number(cart[i].quantity) + Number(quantity);
              cart[i].quantity = num1.toString();
              let num2=Number(addNum1) + Number(quantity);
              addNum1 = num2.toString();
              productExists = true;
              break;
            }
          }
  
          if (productExists) {
            // 如果商品已存在，更新购物车信息
            db.query(
              'UPDATE new_users SET cart = ?, addNum = ? WHERE id = ?',
              [JSON.stringify(cart), addNum1, userId],
              (err, updateResult) => {
                if (err) {
                  return res.send({ status: 500, message: '更新购物车失败' });
                }
                return res.send({ status: 200, message: '商品已添加到购物车', addNum: addNum1, cart: cart });
              }
            );
          } else {
            // 如果商品不存在，添加新商品
            cart.push({ productId, quantity, price,imageUrl,description });
            addNum1 += quantity;  // 更新商品数量
  
            db.query(
              'UPDATE new_users SET cart = ?, addNum = ? WHERE id = ?',
              [JSON.stringify(cart), addNum1, userId],
              (err, insertResult) => {
                if (err) {
                  return res.send({ status: 500, message: '添加购物车失败' });
                }
                return res.send({ status: 200, message: '商品已添加到购物车', addNum: addNum1, cart: cart });
              }
            );
          }
        } else {
          return res.send({ status: 404, message: '用户不存在' });
        }
      }
    );
  };
  //获得购物车数据
  const getCart = (req, res) => {
    const {userId} = req.query;
  
    if (!userId) {
      return res.send({ status: 412, message: '请求参数不完整' });
    }
  
    db.query(
      'SELECT cart,addNum FROM new_users WHERE id = ?',
      [userId],
      (err, results) => {
        if (err) {
          return res.send({ status: 500, message: '查询购物车失败' });
        }
  
        if (results.length > 0) {
          let cart = results[0].cart;
          let addNum = results[0].addNum;
          res.send({ status: 200, data: cart,addNum });
        } else {
          res.send({ status: 404, message: '用户不存在或无购物车数据' });
        }
      }
    );
  };
  //修改购物车数据
  const updateCart = (req, res) => {
    const { userId, productId, quantity } = req.body;
  
    if (!userId || !productId || !quantity) {
      return res.send({ status: 400, message: '请求参数不完整' });
    }
  
    db.query(
      'SELECT cart,addNum FROM new_users WHERE id = ?',
      [userId],
      (err, results) => {
        if (err) {
          return res.send({ status: 500, message: '查询购物车失败' });
        }
        if (results.length > 0) {
          let cart = results[0].cart;
          let addNum = results[0].addNum;
          if (!Array.isArray(cart)) {
            return res.send({ status: 400, message: '购物车数据格式不正确' });
          }
          let productExists = false;
          for (let i = 0; i < cart.length; i++) {
            if (cart[i].productId === productId) {
              let num2=Number(addNum) + Number(quantity)-Number(cart[i].quantity);
              let num1=Number(quantity);
              cart[i].quantity = num1.toString();
              addNum = num2.toString();
              productExists = true;
              break;
            }
          }
          if (productExists) {
            db.query(
              'UPDATE new_users SET cart = ?,addNum=? WHERE id = ?',
              [JSON.stringify(cart),addNum, userId],
              (err, updateResult) => {
                if (err) {
                  return res.send({ status: 500, message: '更新购物车失败' });
                }
                return res.send({ status: 200, message: '商品数量已修改', data: cart,addNum });
              }
            );
          } else {
            return res.send({ status: 404, message: '商品不存在于购物车中' });
          }
         }
        }
      )
    }
  //清空购物车
  const clearCart = (req, res) => {
    const { userId } = req.body;
  
    if (!userId) {
      return res.send({ status: 400, message: '请求参数不完整' });
    }
  
    db.query(
      'UPDATE new_users SET cart = ?,addNum=? WHERE id = ?',
      [JSON.stringify([]),'0', userId],
      (err, results) => {
        if (err) {
          return res.send({ status: 500, message: '清空购物车失败' });
        }
        res.send({ status: 200, message: '购物车已清空' });
      }
    );
  };
  //删除商品
  const deleteProduct = (req, res) => {
    const { userId, productId } = req.body;
  
    if (!userId || !productId) {
      return res.send({ status: 400, message: '请求参数不完整' });
    }
  
    db.query(
      'SELECT cart,addNum FROM new_users WHERE id = ?',
      [userId],
      (err, results) => {
        if (err) {
          return res.send({ status: 500, message: '查询购物车失败' });
        }
        if (results.length > 0) {
          let cart = results[0].cart;
          if (!Array.isArray(cart)) {
            return res.send({ status: 400, message: '购物车数据格式不正确' });
          }
          for (let i = 0; i < cart.length; i++) {
            if (cart[i].productId === productId) {
              let addNum = (Number(results[0].addNum)-Number(cart[i].quantity)).toString();
              cart.splice(i, 1);
              db.query(
                'UPDATE new_users SET cart = ?,addNum=? WHERE id = ?',
                [JSON.stringify(cart), addNum,userId],
                (err, updateResult) => {
                  if (err) {
                    return res.send({ status: 500, message: '删除商品失败' });
                  }
                  res.send({ status: 200, message: '商品已从购物车中移除', data: cart,addNum });
                }
              );
              break;
            }
          }
        }
      }
    )
  }
  //修改整个购物车的数据
  const updateCartLists=(req,res)=>{
    const { userId, cart } = req.body;
    if (!userId || !cart) {
      return res.send({ status: 400, message: '请求参数不完整' });
    }
    //计算总数
    let addNum = '0';
    for (const item of cart) {
      addNum = Number(addNum) + Number(item.quantity);
    }

    //将原有购物车的数据变为传过来的数据
    db.query(
      'UPDATE new_users SET cart = ?, addNum = ? WHERE id = ?',
      [JSON.stringify(cart),addNum, userId],
      (err, results) => {
        if (err) {
          return res.send({ status: 500, message: '更新购物车失败' });
        }
        res.send({ status: 200, message: '购物车已更新', data: cart });
      }
    );
  }
  
module.exports={
   getPicLunBo,
    getPicDaoHan,
    getPicLike,
    getTransform,  
    addCart,
    getCart,
    updateCart,
    clearCart, 
    deleteProduct,
    updateCartLists
}